package br.com.tecnoria.controllers
{
	import br.com.tecnoria.vo.UserVO;
	
	import mx.collections.ArrayCollection;
	import mx.controls.Alert;
	import mx.rpc.events.FaultEvent;
	import mx.rpc.events.ResultEvent;
	import mx.rpc.remoting.mxml.RemoteObject;
	
	import org.swizframework.utils.services.ServiceHelper;

	public class UserController
	{
		[Inject("userRemote")]
		public var remote:RemoteObject;
		
		[Inject]
		public var serviceHelper:ServiceHelper;
		
		[Bindable]
		public var dataprovider:ArrayCollection;
		
		[Bindable]
		public var user:UserVO;
		
		
		
		/**
		 * Call Function
		 */
		
		[EventHandler(event="UserEvent.SAVE", properties="user")]
		public function saveUser(user:UserVO):void
		{
			serviceHelper.executeServiceCall(remote.saveUser(user), onSaveUser, onFault);
		}
		
		[EventHandler(event="UserEvent.LIST")]
		public function listUser():void
		{
			serviceHelper.executeServiceCall(remote.listUser(), onListUser, onFault);
		}
				
		[EventHandler(event="UserEvent.UPDATE", properties="user")]
		public function updateUser(user:UserVO):void
		{
			serviceHelper.executeServiceCall(remote.updateUser(user), onUpdateUser, onFault);
		}
		
		[EventHandler(event="UserEvent.DELETE", properties="user")]
		public function deleteUser(user:UserVO):void
		{
			serviceHelper.executeServiceCall(remote.deleteUser(user), onDeleteUser, onFault);
		}
		
		[EventHandler(event="UserEvent.SEARCH", properties="user")]
		public function searchUser(user:UserVO):void
		{
			serviceHelper.executeServiceCall(remote.searchUser(user.name), onListUser, onFault);
		}
		
		
		/**
		 * Result Function
		 */
		
		public function onSaveUser(result:ResultEvent):void
		{
			Alert.show("Usuário salvo com sucesso!");
			user = new UserVO(result.result);
		}
		
		public function onListUser(result:ResultEvent):void
		{
			dataprovider = new ArrayCollection(result.result as Array);
		}
		
		public function onUpdateUser(result:ResultEvent):void
		{
			Alert.show("Usuário alterado com sucesso!");
			user = new UserVO(result.result);
		}
		
		public function onDeleteUser(result:ResultEvent):void
		{
			Alert.show("Usuário removido com sucesso!");
			listUser();
		}
		
		
		
		/**
		 * Fault Function
		 */
		
		public function onFault(result:FaultEvent):void
		{
			Alert.show(result.fault.toString(), "Erro");
		}
	}
}